<template>
  <div>
    <el-form ref="imgForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="老人编号" prop="id">
        <el-input v-model.trim="form.id" :disabled="true" placeholder="老人编号">
          <el-button slot="append" @click="clickNew">重新生成</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="老人姓名" prop="name">
        <el-input v-model.trim="form.name" placeholder="老人姓名">
          <el-button slot="append" @click="clickSearch">搜索老人</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="老人住址" prop="address">
        <el-input v-model.trim="form.address" :maxlength="60" placeholder="老人住址"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idcard">
        <el-input v-model.trim="form.idcard" placeholder="身份证号"></el-input>
      </el-form-item>
       <el-form-item label="图片类型" class="d2-ml-10">
        <el-radio-group v-model="status" @change="changeStatus">
          <el-radio label="0">抓拍头像上传</el-radio>
          <el-radio label="1">选择头像上传</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="status == '1'" label="老人头像" prop="image">
        <el-upload
          action="#"
          class="manage-uploader"
          accept="image/*"
          :show-file-list="false"
          :on-change="changePictureUploadAvatar"
          :auto-upload="false">
            <img v-if="form.image" :src="form.image" class="older-avatar">
            <i v-else class="el-icon-plus imgs-uploader-icon" aria-hidden="true"></i>
        </el-upload>
        <p class="contract-text d2-mt-10">请保证图片格式正确，且不超过2M</p>
      </el-form-item>
      <el-form-item v-else label="老人头像" prop="image">
        <div class="older-uploader" @click="dialogImgVisible = true">
          <img v-if="form.image" class="older-avatar" :src="form.image" alt="">
          <i v-else class="el-icon-plus imgs-uploader-icon" aria-hidden="true"></i>
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="msg">
        <el-input type="textarea" v-model="form.msg" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-form-item class="contacts-add">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="cancle">关闭</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="老人头像" :close-on-click-modal="false" width="800px" :visible.sync="dialogImageVisible" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!--添加弹窗-->
    <el-dialog
      title="老人头像选择"
      v-if="dialogImgVisible"
      :visible.sync="dialogImgVisible"
      width="600px"
      :append-to-body="true"
      :close-on-click-modal="false">
        <el-row :gutter="10">
          <el-col :span="8" v-for="(item, index) in faceList" :key="index" >
            <div class="older-image" :class="{ 'zhuapai_active': index == selectIndex }" @click="handleSelect(index)">
              <img :src="item" >
            </div>
          </el-col>
        </el-row>
        <div class="older-footer">
          <el-button type="primary" @click="sureImg">确定</el-button>
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 老人列表 -->
    <el-drawer title="老人列表" :size="1000" :visible.sync="dialogOlderVisible" :destroy-on-close="true" @close="dialogOlderVisible = false" :wrapperClosable="false" :with-header="false" :modal="false" direction="rtl">
      <older-list @close="dialogOlderVisible = false" :name="olderName" @sure="sure"></older-list>
    </el-drawer>
  </div>
</template>

<script>
 const validateCard = (rule, value, callback) => {
   if(!value){
     callback();
   } else if (!isIdCard(value)) {
     callback(new Error("请输入正确的身份证"));
   } else {
     callback();
   }
 };
import * as APIDailycare from '@/api/dailycare'
import { mapState } from 'vuex'
import * as RegExp from '@/utils/RegExp'
import dayjs from 'dayjs'
import olderList from './older-list'
import { isIdCard, isPhone } from "@/utils/validate";
import { uploadCameraFilePromise, uploadFilePromise } from '@/api/upload'
export default {
  name: 'older-add',
  components: {
    olderList
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapState('facewebsocket', [
      'deviceMsg',
      'sendFaceMsg'
    ])
  },
  data () {
    return {
      // 老人姓名
      olderName: '',
      dialogOlderVisible: false,
      // 显示图标窗口
      dialogVisible: false,
      dialogImgVisible: false,
      selectIndex: 0,
      iconList: [],
      list: [],
      typeList: [],
      form: {},
      // 0 自动上传 1 手动上传
      status: '0',
      dialogImageUrl: '',
      dialogImageVisible: false,
      // 完整base64图片
      baseUrl: '',
      // 表单校验
      rules: {
        id: [
          { required: true, message: '重新生成老人id', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入老人姓名', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入老人住址', trigger: 'blur' }
        ],
        idcard: [
          /* {
            pattern: RegExp.IDCard,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }, */
          { message: "请输入身份证号", trigger: "blur" },
          { validator: validateCard, trigger: "blur" },
        ],
        image: [
          {
            required: true,
            message: '请上传老人头像',
            trigger: 'blur'
          }
        ]
      },
      fileList: [],
      faceList: []
    }
  },
  mounted () {
    this.form = { ...this.form, ...{ id: dayjs().format('YYYYMMDDHHmmss') } }
  },
  watch: {
    sendFaceMsg: {
      handler: function (newVal) {
        this.init(newVal, this)
      }
    },
    deviceMsg: {
      handler: function (newVal) {
        this.faceinit(newVal, this)
      }
    }
  },
  methods: {
    faceinit (data, _that) {
      /* const { info } = _that
      let device_sn = ''
      if (info.face && info.face.length !== 0) {
        info.face.forEach(item => {
          if (item.type === '1') {
            device_sn = item.device_sn || ''
          }
        })
      } */
      let device_sn = ''
      let userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
            userinfo.facedev.forEach(item => {
               device_sn = item.device_sn || ''
            })
        }
      }
      if (data.route == 'face') {
        if (device_sn == data.data.device_sn) {
          const closeup_pic = data.data.closeup_pic
          const personImg = closeup_pic.format == 'jpg' ? 'data:image/jpg;base64,' + closeup_pic.data : closeup_pic.format === 'png' ? 'data:image/png;base64,' + closeup_pic.data : 'data:image/jpeg;base64,' + closeup_pic.data
          _that.faceList.push(personImg)
          if (device_sn) {
            const senddata = {
              cmd: 'send_dev',
              device_sn: device_sn,
              data: {
                cmd: 'tts play',
                text: '扫脸成功'
              }
            }
            _that.$face.$ws.send(JSON.stringify(senddata))
          }
        }
      }
    },
    init (data, _that) {
      /* const { info } = _that
      let device_sn = ''
      if (info.face && info.face.length !== 0) {
        info.face.forEach(item => {
          if (item.type === '1') {
            device_sn = item.device_sn || ''
          }
        })
      } */
      let device_sn = ''
      let userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
            userinfo.facedev.forEach(item => {
               device_sn = item.device_sn || ''
            })
        }
      }
      if (data.cmd == 'upload person' && data.reply == 'ACK') {
        let msg = ''
        switch (data.code) {
          case 0:
            msg = '人员导入成功'
            break
          case 3:
            msg = data.desc || '数据格式错误，请联系管理员'
            break
          case 6:
            msg = '设备内存不足，请清理设备内多余信息'
            break
          case 16:
            msg = '人员可能已存在，请查看人脸库'
            break
          case 20:
            msg = '设备人员录入已满'
            break
          case 21:
            msg = '人员记录已存在'
            break
          case 22:
            msg = '人脸记录不存在，可以添加'
            break
          case 25:
            msg = '提取成员失败，请检查上次图片'
            break
          case 35:
            msg = '图片解码失败，请选择jpg或png图片上传'
            break
          case 36:
            msg = '图片太大，请上传4M大小以内图片'
            break
          case 38:
            msg = '图片人脸尺寸太小，请选择合适图片上传'
            break
          case 39:
            msg = '图片人脸质量太差，请选择清晰图片上传'
            break
          case 40:
            msg = '图片中存在多张人脸，请选择单张人脸图片上传'
            break
          case 41:
            msg = '图片中人脸不完整，请选择完整人脸图片上传'
            break
        }
        if (data.code == 0) {
          const form = { ..._that.form, ...{ image: _that.baseUrl } }
          APIDailycare.riolderAdd(form).then(res => {
            _that.cancle()
            _that.load()
            _that.$message.success(msg)
          })
        } else {
          _that.$message.error(msg)
        }
        if (device_sn) {
          const senddata = {
            cmd: 'send_dev',
            device_sn: device_sn,
            data: {
              cmd: 'tts play',
              text: msg
            }
          }
          _that.$face.$ws.send(JSON.stringify(senddata))
        }
      }
    },
    clickNew () {
      this.form = { ...this.form, ...{ id: dayjs().format('YYYYMMDDHHmmss') } }
    },
    clickSearch () {
      if (!this.form.name) {
        this.$message.warning('请先输入姓名')
        return false
      }
      this.olderName = this.form.name
      this.dialogOlderVisible = true
    },
    // 确定搜索的老人
    sure (row) {
      this.form = {
        ...this.form,
        ...{
          name: row.name,
          address: row.address,
          idcard: row.id_card
        }
      }
    },
    handleSelect (index) {
      this.selectIndex = index
      const image = this.faceList[index]
      this.form = { ...this.form, ...{ image } }
    },
    sureImg () {
      const image = this.faceList[this.selectIndex]
      this.form = { ...this.form, ...{ image } }
      this.dialogImgVisible = false
      const blob = this.dataURLtoFile(image)
      const file = new File([blob], 'file', {
        type: blob.type,
        lastModified: Date.now()
      })
      uploadCameraFilePromise(file).then(res => {
        this.baseUrl = res.data;
      })
    },
    /** base64转为文件上传 */
    dataURLtoFile (dataURI) {
      const binary = atob(dataURI.split(',')[1])
      const array = []
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], { type: 'image/jpeg' })
    },
    // 上传图片
    changePictureUploadAvatar (file, fileList) {
      this.fileList = fileList
      this.getImageUrlBase64(file.raw)
      uploadFilePromise(file).then(res => {
        this.baseUrl = res.data;
      })
    },
    // 放大图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    /** 获取老人头像base64编码 */
    getImageUrlBase64 (file) {
      const _this = this
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          const result = reader.result
          const image = new Image()
          // 解决跨域问题
          image.setAttribute('crossOrigin', 'anonymous')
          image.src = result
          // image.onload为异步加载
          image.onload = () => {
            const canvas = document.createElement('canvas')
            canvas.width = image.width
            canvas.height = image.height
            const context = canvas.getContext('2d')
            context.drawImage(image, 0, 0, image.width, image.height)
            // 这里的imgResult就是base64类型
            imgResult = canvas.toDataURL('image/jpeg', 1)
            _this.form = { ..._this.form, ...{ image: imgResult } }
            _this.baseUrl = imgResult
          }
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    // 删除图片
    handleRemove (file) {
      this.fileList.forEach((item, index) => {
        if (item.name === file.name) {
          this.fileList.splice(index, 1)
        }
      })
      if (this.fileList.length === 0) {
        this.form = { ...this.form, ...{ image: '' } }
      }
    },
    changeStatus (status) {
      this.status = status
      this.form = { ...this.form, ...{ image: '' } }
    },
    // 添加
    onSubmit () {
      // const { info } = this
      let device_sn = ''
      let userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
            userinfo.facedev.forEach(item => {
               device_sn = item.device_sn || ''
            })
        }
      }
      /* if (info.face && info.face.length !== 0) {
        info.face.forEach(item => {
          if (item.type === '1') {
            device_sn = item.device_sn || ''
          }
        })
      } */
      this.$refs.imgForm.validate((valid) => {
        if (valid) {
          const { id, name, address, image } = this.form
          const imageUrl = image.split(',')[1]
          const senddata = {
            cmd: 'send_dev',
            device_sn: device_sn,
            data: {
              cmd: 'upload person',
              id: id,
              name: name,
              reg_image: imageUrl,
              long_card_id: Number(id),
              customer_text: address,
              upload_mode: 0
            }
          }
          this.$face.$ws.send(JSON.stringify(senddata))
        }
      })
    },
    load () {
      this.$emit('load')
    },
    cancle () {
      this.$refs.imgForm.resetFields()
      this.$emit('cancle')
    }
  }
}
</script>

<style lang="scss">
.el-select{
  width: 100%;
}
.el-date-editor.el-input{
  width: 100%;
}
.type-add-input {
  textarea {
    font-family: arial;
  }
}
i.icon-uploader-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  vertical-align: bottom;
}
.task-image {
  width: 80px;
  height: 80px;
  position: absolute;
  cursor: pointer;
  border: 1px solid #f5f7fa;
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
  }
  &:hover {
    // border: 1px dashed $theme-table-button-view-text-color;
  }
  i {
    font-size: 20px;
  }
}
.task-form-item {
  height: 33px;
}
.older-image {
  border: 1px solid transparent;
  box-sizing: border-box;
  width: 100%;
  height: 220px;
  img {
    width: 100%;
    height: 100%;
  }
}
.zhuapai_active {
  position: relative;
  width:100%;
  height: 220px;
  margin: 0 auto;
  text-align: center;
  color: #4ABE84;
  background-color: #fff;
  box-shadow:0px 2px 7px 0px rgba(85,110,97,0.35);
  border-radius:7px;
  border:1px solid rgba(74,190,132,1);
  box-sizing: border-box;
}
.zhuapai_active:before {
  content: '';
  position: absolute;
  right: 0;
  bottom: 0;
  border: 17px solid #4ABE84;
  border-top-color: transparent;
  border-left-color: transparent;
}
.zhuapai_active:after {
  content: '';
  width: 5px;
  height: 12px;
  position: absolute;
  right: 6px;
  bottom: 6px;
  border: 2px solid #fff;
  border-top-color: transparent;
  border-left-color: transparent;
  transform: rotate(45deg);
}
.older-uploader {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fbfdff;
}
.manage-uploader {
	.el-upload {
		width: 148px;
		height: 148px;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
    background-color: #fbfdff;
	}
}
.manage-uploader .el-upload:hover {
	border-color: #409EFF;
}
.older-avatar {
  width: 100%;
  height: 100%;
}
.older-footer {
  margin-top: 20px;
  text-align: right;
}
i.imgs-uploader-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 50px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    vertical-align: bottom;
  }
</style>
